
import warnings
from django.utils.encoding import force_str
from rest_framework import RemovedInDRF317Warning
from django.utils.translation import gettext_lazy as _


from django.shortcuts import render
import json
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from django.conf import settings
import os


# Create your views here.
from .serializers import *
from rest_framework import viewsets
from .models import *


from rest_framework.pagination import PageNumberPagination
from rest_framework.decorators import action

# Create your views here.
from django_filters.rest_framework import DjangoFilterBackend, CharFilter

from django_filters import FilterSet, DateFilter

from django.utils.timezone import make_aware
from datetime import datetime, timedelta

from django.http import HttpResponse
from datetime import datetime

# views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework.schemas import AutoSchema, coreapi
import coreschema

# from rest_framework.schemas.openapi import AutoSchema
from rest_framework import serializers
from coreapi import Field
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.db.models import F


class MyPagination(PageNumberPagination):
    page_size = 20  # 设置默认分页长度为10
    page_size_query_param = "page_size"  # 允许通过查询参数改变分页长度
    max_page_size = 100  # 最大分页长度

    project_param = "project"
    project_query_description = _("项目")
    page_query_param = "page"
    page_query_description = _("要查询哪一页？")
    page_size_query_description = _("每页要查询多少条数据？")

    def get_schema_fields(self, view):
        assert coreapi is not None, "coreapi must be installed to use `get_schema_fields()`"
        if coreapi is not None:
            warnings.warn(
                "CoreAPI compatibility is deprecated and will be removed in DRF 3.17", RemovedInDRF317Warning
            )
        assert coreschema is not None, "coreschema must be installed to use `get_schema_fields()`"
        fields = [
            Field(
                name=self.page_query_param,
                required=False,
                location="query",
                schema=coreschema.Integer(title="Page", description=force_str(self.page_query_description)),
            ),
        ]
        if self.page_size_query_param is not None:
            fields.append(
                Field(
                    name=self.page_size_query_param,
                    required=False,
                    location="query",
                    schema=coreschema.Integer(
                        title="Page size", description=force_str(self.page_size_query_description)
                    ),
                )
            )
        return fields


# Create your views here.
class StationStatusViewSet(viewsets.ModelViewSet):
    queryset = StationStatus.objects.all()
    serializer_class = StationStatusSerializer
    # 这是视图级别配置分页
    pagination_class = MyPagination

    @action(detail=False, methods=["get"])
    def custom_list(self, request):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class AndonCallViewSet(viewsets.ModelViewSet):
    queryset = AndonCall.objects.all()
    serializer_class = AndonCallSerializer
    # 这是视图级别配置分页
    pagination_class = MyPagination

    @action(detail=False, methods=["get"])
    def custom_list(self, request):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class andonCall(APIView):
    pass


class my_andonCall(APIView):
    # 设置默认的每页数据量
    page_size = 10
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            # Field(name="id", required=False, location="query", schema=coreschema.Number(description="id")),
            # Field(
            #     name="eun", required=False, location="query", schema=coreschema.String(description="发动机号")
            # ),
            Field(
                name="sub_area",
                required=False,
                location="query",
                schema=coreschema.String(description="区域"),
            ),
            # Field(
            #     name="station_type",
            #     required=False,
            #     location="query",
            #     schema=coreschema.String(description="工位类型(A:自动站;M;手动站)"),
            # ),
            Field(
                name="page", required=False, location="query", schema=coreschema.String(description="第几页")
            ),
            Field(
                name="page_size",
                required=False,
                location="query",
                schema=coreschema.String(description="页面大小"),
            ),
            Field(
                name="start_time",
                required=False,
                location="query",
                schema=coreschema.String(description="开始日期时间，格式示例：2024-07-01 16:34:42"),
            ),
            Field(
                name="end_time",
                required=False,
                location="query",
                schema=coreschema.String(description="结束日期时间，格式示例：2024-07-10 16:34:42"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = AndonCallSerializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        # queryset = OutputLoopa.objects.using("as_manage_analysis").annotate(staion_order=F('staion')).order_by('staion_order')
        queryset = AndonCall.objects.using("default").filter().order_by("start_time")
        # 获取请求的参数

        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)
        print(start_time_param)
        print(end_time_param)

        id = request.query_params.get("id")
        sub_area = request.query_params.get("sub_area")
        # station_type = request.query_params.get("station_type")
        # eun = request.query_params.get("eun")
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = AndonCall.objects.using("default").filter(id=id)
        if sub_area is not None:
            queryset = queryset.filter(sub_area__contains=sub_area)
        if (start_time_param and end_time_param) is not None:
            start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
            end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(
                start_time__gte=start_time_param_trans, start_time__lte=end_time_param_trans
            )
        else:
            print("aaaaa")

        return queryset


class AndonPullCallsViewSet(viewsets.ModelViewSet):
    queryset = AndonPullCalls.objects.all()
    serializer_class = AndonPullCallsSerializer
    # 这是视图级别配置分页
    pagination_class = MyPagination

    @action(detail=False, methods=["get"])
    def custom_list(self, request):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class EquipmentViewSet(viewsets.ModelViewSet):
    queryset = Equipment.objects.all()
    serializer_class = EquipmentSerializer
    # 这是视图级别配置分页
    pagination_class = MyPagination

    @action(detail=False, methods=["get"])
    def custom_list(self, request):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class Top20ShutdownViewSet(viewsets.ModelViewSet):
    queryset = Top20Shutdown.objects.all()
    serializer_class = Top20ShutdownSerializer
    # 这是视图级别配置分页
    pagination_class = MyPagination

    @action(detail=False, methods=["get"])
    def custom_list(self, request):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


# 节拍过滤器
class LastCtFilter(FilterSet):
    class Meta:
        model = LastCtStatistics
        fields = ["sub_area", "equipment_id", "point_id"]


class LastCtStatisticsViewSet(viewsets.ModelViewSet):
    queryset = LastCtStatistics.objects.all()

    serializer_class = LastCtStatisticsSerializer
    # 这是视图级别配置分页
    pagination_class = MyPagination

    filter_backends = [DjangoFilterBackend]
    filterset_class = LastCtFilter

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset

    @action(detail=False, methods=["get"])
    def custom_list(self, request):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


# 自定义分页
class LastCtStatisticsView(APIView):
    def get(self, request, *args, **kwargs):
        queryset = LastCtStatistics.objects.all()
        paginator = MyPagination()
        page = paginator.paginate_queryset(queryset, request)
        serializer_class = LastCtStatisticsSerializer(page, many=True)
        return Response(serializer_class.data)


class MachineFaultHistoryViewSet(viewsets.ModelViewSet):
    queryset = MachineFaultHistory.objects.all()
    serializer_class = MachineFaultHistorySerializer
    # 这是视图级别配置分页
    pagination_class = MyPagination

    @action(detail=False, methods=["get"])
    def custom_list(self, request):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class MachineFaultHistoryView(APIView):
    # 设置默认的每页数据量
    page_size = 10
    # 设置在API DOC的字段显示
    schema = AutoSchema(
        manual_fields=[
            Field(
                name="point_id",
                required=False,
                location="query",
                schema=coreschema.Number(description="point_id"),
            ),
            # Field(
            #     name="eun", required=False, location="query", schema=coreschema.String(description="发动机号")
            # ),
            Field(
                name="sub_area",
                required=False,
                location="query",
                schema=coreschema.String(description="区域"),
            ),
            Field(
                name="equipment_id",
                required=False,
                location="query",
                schema=coreschema.String(description="工位"),
            ),
            Field(
                name="page", required=False, location="query", schema=coreschema.String(description="第几页")
            ),
            Field(
                name="page_size",
                required=False,
                location="query",
                schema=coreschema.String(description="页面大小"),
            ),
            Field(
                name="start_time",
                required=False,
                location="query",
                schema=coreschema.String(description="开始日期时间，格式示例：2024-07-01 16:34:42"),
            ),
            Field(
                name="end_time",
                required=False,
                location="query",
                schema=coreschema.String(description="结束日期时间，格式示例：2024-07-10 16:34:42"),
            ),
        ]
    )

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = AndonCallSerializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        # queryset = OutputLoopa.objects.using("as_manage_analysis").annotate(staion_order=F('staion')).order_by('staion_order')
        queryset = MachineFaultHistory.objects.using("default").filter().order_by("start_time")
        # 获取请求的参数

        start_time_param = request.query_params.get("start_time", None)
        end_time_param = request.query_params.get("end_time", None)

        point_id = request.query_params.get("point_id")
        sub_area = request.query_params.get("sub_area")
        equipment_id = request.query_params.get("equipment_id")
        # 根据参数是否存在添加不同筛选条件
        if point_id is not None:
            queryset = queryset.filter(point_id=point_id)
        if sub_area is not None:
            queryset = queryset.filter(sub_area__contains=sub_area)
        if equipment_id is not None:
            queryset = queryset.filter(equipment_id__contains=equipment_id)
        if (start_time_param and end_time_param) is not None:
            start_time_param_trans = datetime.strptime(start_time_param, "%Y-%m-%d %H:%M:%S")
            end_time_param_trans = datetime.strptime(end_time_param, "%Y-%m-%d %H:%M:%S")
            print(start_time_param_trans)
            print(end_time_param_trans)
            queryset = queryset.filter(
                start_time__gte=start_time_param_trans, start_time__lte=end_time_param_trans
            )
        else:
            print("aaaaa")

        return queryset


class ProductionHourlyViewSet(viewsets.ModelViewSet):
    queryset = ProductionHourly.objects.all()
    serializer_class = ProductionHourlySerializer
    # 这是视图级别配置分页
    pagination_class = MyPagination

    @action(detail=False, methods=["get"])
    def custom_list(self, request):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class ScheduleViewSet(viewsets.ModelViewSet):
    queryset = Schedule.objects.all()
    serializer_class = ScheduleSerializer
    # 这是视图级别配置分页
    pagination_class = MyPagination

    @action(detail=False, methods=["get"])
    def custom_list(self, request):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


# 刀具记录过滤器
class ToolChangeLogFilter(FilterSet):
    class Meta:
        model = ToolChangeLog
        project = CharFilter(field_name="project", help_text="过滤标题")
        fields = ["project", "sub_area", "equipment"]


class ToolChangeLogViewSet(viewsets.ModelViewSet, FilterSet):
    queryset = ToolChangeLog.objects.all()
    serializer_class = ToolChangeLogSerializer
    # 这是视图级别配置分页
    pagination_class = MyPagination

    filter_backends = [DjangoFilterBackend]
    filterset_class = ToolChangeLogFilter

    # 根据前端传递的参数自定义查询集
    def get_queryset(self):
        queryset = super().get_queryset()
        # query_params = self.request.query_params
        # equipment_param = query_params.get("equipment", None)

        # if equipment_param:
        #     queryset = queryset.filter(equipment=equipment_param)
        #     print("这是" + str(equipment_param))

        return queryset

    @action(detail=False, methods=["get"])
    def custom_list(self, request):
        queryset = self.get_queryset()

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


# 测试用
class test(APIView):
    authentication_classes = []

    data_frombackend1 = {
        "op2060": [
            {"name": "设备停机", "start_time": "2023-03-01 09:00:00", "end_time": "2023-03-01 09:10:00"},
            {"name": "满位", "start_time": "2023-03-01 09:10:00", "end_time": "2023-03-01 09:13:00"},
            {"name": "有托盘", "start_time": "2023-03-01 09:13:00", "end_time": "2023-03-01 09:15:00"},
            {"name": "无托盘", "start_time": "2023-03-01 09:15:00", "end_time": "2023-03-01 09:27:00"},
            {"name": "设备故障", "start_time": "2023-03-01 09:27:00", "end_time": "2023-03-01 09:31:00"},
            {"name": "空位", "start_time": "2023-03-01 09:31:00", "end_time": "2023-03-01 09:33:00"},
        ],
        "op2070": [
            {"name": "有托盘", "start_time": "2023-03-01 09:00:00", "end_time": "2023-03-01 09:13:10"},
            {"name": "满位", "start_time": "2023-03-01 09:13:10", "end_time": "2023-03-01 09:15:10"},
            {"name": "有托盘", "start_time": "2023-03-01 09:15:00", "end_time": "2023-03-01 09:19:00"},
            {"name": "无托盘", "start_time": "2023-03-01 09:19:00", "end_time": "2023-03-01 09:29:00"},
            {"name": "设备故障", "start_time": "2023-03-01 09:29:00", "end_time": "2023-03-01 09:39:00"},
            {"name": "空位", "start_time": "2023-03-01 09:39:00", "end_time": "2023-03-01 09:43:00"},
        ],
        "op2080": [
            {"name": "有托盘", "start_time": "2023-03-01 09:00:00", "end_time": "2023-03-01 09:05:10"},
            {"name": "满位", "start_time": "2023-03-01 09:05:10", "end_time": "2023-03-01 09:10:10"},
            {"name": "有托盘", "start_time": "2023-03-01 09:10:10", "end_time": "2023-03-01 09:11:00"},
            {"name": "无托盘", "start_time": "2023-03-01 09:11:00", "end_time": "2023-03-01 09:47:00"},
            {"name": "设备故障", "start_time": "2023-03-01 09:47:00", "end_time": "2023-03-01 09:49:00"},
            {"name": "空位", "start_time": "2023-03-01 09:49:00", "end_time": "2023-03-01 09:53:00"},
        ],
        "op2090": [
            {"name": "有托盘", "start_time": "2023-03-01 09:00:00", "end_time": "2023-03-01 09:03:10"},
            {"name": "满位", "start_time": "2023-03-01 09:03:10", "end_time": "2023-03-01 09:05:10"},
            {"name": "有托盘", "start_time": "2023-03-01 09:05:00", "end_time": "2023-03-01 09:19:00"},
            {"name": "无托盘", "start_time": "2023-03-01 09:19:00", "end_time": "2023-03-01 09:21:00"},
            {"name": "设备故障", "start_time": "2023-03-01 09:21:00", "end_time": "2023-03-01 09:31:00"},
            {"name": "空位", "start_time": "2023-03-01 09:31:00", "end_time": "2023-03-01 09:43:00"},
        ],
        "长缸体OP2130-2": [
            {"name": "有托盘", "start_time": "2023-03-01 09:00:00", "end_time": "2023-03-01 09:13:10"},
            {"name": "满位", "start_time": "2023-03-01 09:13:10", "end_time": "2023-03-01 09:15:10"},
            {"name": "有托盘", "start_time": "2023-03-01 09:15:00", "end_time": "2023-03-01 09:19:00"},
            {"name": "无托盘", "start_time": "2023-03-01 09:19:00", "end_time": "2023-03-01 09:27:00"},
            {"name": "设备故障", "start_time": "2023-03-01 09:27:00", "end_time": "2023-03-01 09:39:00"},
            {"name": "空位", "start_time": "2023-03-01 09:39:00", "end_time": "2023-03-01 09:43:00"},
        ],
        "冷试OP2210": [
            {"name": "有托盘", "start_time": "2023-03-01 09:00:00", "end_time": "2023-03-01 09:13:10"},
            {"name": "满位", "start_time": "2023-03-01 09:13:10", "end_time": "2023-03-01 09:15:10"},
            {"name": "有托盘", "start_time": "2023-03-01 09:15:00", "end_time": "2023-03-01 09:19:00"},
            {"name": "无托盘", "start_time": "2023-03-01 09:19:00", "end_time": "2023-03-01 09:27:00"},
            {"name": "设备故障", "start_time": "2023-03-01 09:27:00", "end_time": "2023-03-01 09:39:00"},
            {"name": "空位", "start_time": "2023-03-01 09:39:00", "end_time": "2023-03-01 09:43:00"},
        ],
    }

    def get(self, request):
        # quzhou = StationStatus.objects.filter(sub_area="曲轴M1")
        # print(quzhou)
        print("hhhhhhh")
        return Response(self.data_frombackend1)


def test1():
    print("测试")
